/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.gwxs;

import cn.ac.iie.di.datadock.rdata.exchange.client.v1.session.RESendSession;
import cn.ac.iie.di.global.GlobalParas;
import cn.ac.iie.di.tools.MMUrlPath;
import cn.ac.iie.di.gwxs.JsonGwxSender.SessionPool;
import cn.ac.iie.di.tools.GenerateMD5;
import cn.ac.iie.di.tools.GetIpTools;
import cn.ac.iie.di.tools.TimeFormat;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 *
 * @author lenovo-pc
 */
public class JsonGwxTask1 implements Runnable {

    private final List<String> jsonList;

    static private final HashMap<String, String> JsonData;//存储Json中的数据
    static org.apache.log4j.Logger logger = null;

    static {
        logger = org.apache.log4j.Logger.getLogger(JsonGwxTask1.class.getName());
    }

    private SimpleDateFormat formatter;

    static {

        JsonData = new HashMap<>();

    }
    private final SessionPool pool;

    public JsonGwxTask1(List<String> jsonList, SessionPool pool) {
        this.jsonList = jsonList;
        this.pool = pool;
        this.formatter = new SimpleDateFormat("yyyy-MM");
    }

    @Override
    public void run() {
        RESendSession session = null;
        long line = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH");
        Set<String> cc = new HashSet<String>();
        long startTime = System.currentTimeMillis();
        try {
            session = pool.borrowSession();
            logger.debug("asdfzcvetqtert " + jsonList.size());
            for (String json : jsonList) {
                if (json != null && !json.isEmpty()) {
                    try {
//                        long s1 = System.currentTimeMillis();
                        Document document = DocumentHelper.parseText(json.replaceAll("[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]", ""));
                        Element msg = document.getRootElement();
                        List<Element> list = msg.elements();
//                        logger.info("Document time " + (System.currentTimeMillis() - s1));
                        //g_id  根据FromUin+MsgID+Chatroom预处理
                        String key = msg.element("FromUin").getText() + msg.element("MsgID").getText() + msg.element("Chatroom").getText();
                        session.setString("g_id", GenerateMD5.string2MD5(key));
                        session.setString("g_ch_key", GenerateMD5.string2MD5(key));
                        session.setString("g_asp", "WeChat");
                        session.setString("g_adp", "WeChat");
                        if (msg.element("FromTime").getText() != null && !msg.element("FromTime").getText().trim().isEmpty()) {
                            session.setLong("m_publish_time", Long.valueOf(msg.element("FromTime").getText()));
                        } else {
                            session.setLong("m_publish_time", 0);
                        }
                        session.setLong("m_insert_time", -99);
                        session.setLong("m_chat_room", Long.valueOf(msg.element("Chatroom").getText()));
                        session.setString("m_ch_id", msg.element("MsgID").getText());
                        session.setInt("m_type", Integer.valueOf(msg.element("Type").getText()));
                        session.setString("m_content", msg.element("Content").getText());
                        session.setString("m_language", "");
                        session.setString("u_g_ch_key", msg.element("FromUin").getText());
                        session.setString("u_name", msg.element("From").getText());
                        session.setLong("u_ch_id", Long.valueOf(msg.element("FromUin").getText()));
                        session.setString("u_send_ip", msg.element("ClientIP").getText());
//                        session.setString("u_send_ip", "未知");
//                        long s2 = System.currentTimeMillis();
                        int[] addrNum = GetIpTools.getIpAddr(msg.element("ClientIP").getText());
                        //新加字段
                        int dom = 0;
                        if (addrNum[1] < 1000 && addrNum[1] > 100) {
                            dom = -1;
                            session.setInt("m_country_code", addrNum[1]);
                            session.setInt("u_loc_county", -1);
                            session.setInt("u_loc_province", -1);
//                            logger.info("ipipipipip" + addrNum[1] + msg.element("ClientIP").getText());
                        } else {
                            dom = 1;
                            session.setInt("m_country_code", 150);
                            session.setInt("u_loc_county", addrNum[0]);
                            session.setInt("u_loc_province", Integer.valueOf(addrNum[1] + "0000"));
                        }
//                        logger.info("Document time " + (System.currentTimeMillis() - s2));
                        session.setInt("m_dom_for", dom);
                        session.setLong("m_mm_id", Long.valueOf(msg.element("MediaID").getText()));
                        int type = Integer.valueOf(msg.element("Type").getText());
                        if (type != 1 && type != 37 && type != 36 && type != 40 && type != 51 && type != 4000 && type != 9999) {
                            String[] feature = null;
                            Document d = DocumentHelper.parseText(msg.element("Content").getText().replaceAll("[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]", ""));
                            Element rootElement = d.getRootElement();
                            List<Element> eles = rootElement.elements();
                            for (Element ele : eles) {
                                List<Attribute> attrs = ele.attributes();
                                feature = new String[attrs.size()];
                                for (int i = 0; i < attrs.size(); i++) {
                                    feature[i] = attrs.get(i).getText();
                                }
                            }
                            if (feature == null) {
                                session.setStrings("m_mm_feature", new String[0]);
                            } else {
                                session.setStrings("m_mm_feature", feature);
                            }

                        } else {
//                            String[] feature = {msg.element("Content").getText()};
                            session.setStrings("m_mm_feature", new String[0]);
                        }

                        session.setLongs("m_themes_list", new long[]{});
                        session.setLongs("m_topics_list", new long[]{});
                        session.setLongs("m_rules_list", new long[]{});
//                        session.setInt("m_msg_cnt", 0);
                        String[] time = new TimeFormat().getTimeString(Long.valueOf(msg.element("FromTime").getText())).split("-");
                        session.setInt("m_year", Integer.valueOf(time[0]));
                        session.setInt("m_month", Integer.valueOf(time[1]));
                        session.setInt("m_day", Integer.valueOf(time[2]));
                        session.setInt("m_hour", Integer.valueOf(time[3]));
                        session.setString("m_mm_content", "");
                        try {
                            session.setString("m_mm_url", msg.element("MediaURL").getText());
                        } catch (Exception e) {
                            session.setString("m_mm_url", "");
                        }

                        try {
                            session.add();
                            line++;
                        } catch (Exception e) {
                            sendMSG(session);
                            logger.info("GMSG successful send " + line);
                            line = 0;
                            session.add();
                            line++;
                        }

                    } catch (Exception ex) {
                        logger.warn("The session add is wrong:" + ex + "error msg" + json, ex);
                    }

                }
            }
            sendMSG(session);
            long endTime = System.currentTimeMillis();
            logger.info("GMSG successful send " + line + " Send Time is " + (endTime - startTime));
            line = 0;

        } catch (Exception ex) {
            logger.error("know News Task error ", ex);
            ex.printStackTrace();
        } finally {
            if (session != null) {
                pool.returnSession(session);
            }
        }
    }

    public void sendMSG(RESendSession session) {
        while (true) {
            try {
                session.flush();
                break;
            } catch (Exception ex) {
                logger.info("what's up buddy ? how's it going ?" + ex, ex);
            }
        }
    }
}
